package net.sareweb.acab.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.ejb.Stateful;
import javax.ejb.Stateless;


import net.sareweb.acab.entity.User;
import net.sareweb.acab.entity.manager.UserManager;
import net.sareweb.acab.session.Authenticator;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.core.Events;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.management.IdentityManager;


@Name("registerBean")
@Scope(ScopeType.CONVERSATION)
public class RegisterBean{// implements RegisterBeanInterface{
	
	@Logger
	private Log log;
	 
	@Out(required=false)
	private User user;

	@In(create=true)
	UserManager userManager;
	
	@In Identity identity;
	@In IdentityManager identityManager; 
	@In Credentials credentials;
	
	public String createAction() throws NoSuchAlgorithmException, UnsupportedEncodingException{
		log.debug("About to create a user named {0}", user.getLogin());
		if(!userManager.existsLoginName(user.getLogin())){
			String plainPass=user.getPassword();
			user.setPassword(Authenticator.SHA1(user.getPassword()));
			userManager.save(user);
			credentials.clear();
			credentials.setUsername(user.getLogin());
			credentials.setPassword(plainPass);
			identity.login();
			
			Events.instance().raiseEvent("userCreatedEvent", user);
			return "userCreated";
		}
		else{
			log.debug("Exists a user with login {0}", user.getLogin());
			return "";
		}
	}

	@Factory(value="user")
	public void instantiateUser(){
		if(this.user==null){
			log.debug("Instantiating user", "");
			this.user= new User();
		}
	}
	
	@Factory("userManager")
	public void instantiateUserManager(){
		if(this.userManager==null){
			log.debug("Instantiating userManager", "");
			this.userManager= new UserManager();
		}
	}
	
	
	
	
	

	
}
